package cn.cd.anStudio.io;

import java.util.Vector;

import android.text.format.Time;
import android.util.Log;
import cn.cd.anStudio.MyBusCommonBase;
import cn.cd.anStudio.MyBusInfo;
import cn.cd.anStudio.util.MyBusCommonUtil;
import cn.cd.anStudio.util.MyBusXMLParser;

public class MyBusNetUtil {
	
	private static final String TAG = "MyBusNetUtil";
	
	public static final int BUS_LOCATION_QUERY_TYPE_UP     = 1;
	public static final int BUS_LOCATION_QUERY_TYPE_DOWN  = 2;
	public static final int BUS_LOCATION_QUERY_TYPE_CIRCLE = 3;
	
	public MyBusNetUtil() {
		super();
		if (MyBusCommonBase.DEBUG)
			Log.v(TAG, "Generate bus util instance");
	}
	
	public MyBusInfo getBusInfoByNet(String busNum) {
		
		int myBusRouteType = MyBusInfo.BUS_UNKNOWN_DIRECTION;
		Vector<Time> myBusTime;
		Vector<String> busStops1;
		Vector<String> busStops2;
		
		MyBusInfo busInfo = new MyBusInfo(busNum);

		String locReqURI = MyBusCommonBase.SERVER
				+ MyBusCommonBase.BUSLINE_SERVICE_REQUEST
				+ MyBusCommonBase.KEY_BUS_ID + "=" + busNum + "&"
				+ MyBusCommonBase.KEY_TYPE + "=0&"
				+ MyBusCommonBase.KEY_PAGE + "=1";
		
		if (MyBusCommonBase.DEBUG)
			Log.v(TAG, "getBusInfoByNet from " + locReqURI);

		myBusRouteType = MyBusXMLParser.getBusRouteTypeFromHtml(locReqURI);
		busInfo.setRouteType(myBusRouteType);
		
		myBusTime = MyBusXMLParser.getBusTimeFromHtml(locReqURI);
		if (myBusTime != null) {
			busInfo.setStartTime(myBusTime.elementAt(0));
			busInfo.setEndTime(myBusTime.elementAt(1));
		}
		
		busStops1 = MyBusXMLParser.getBusStopsFromHtml(busNum, 0);
		if (busStops1.size() > 0) {
			busInfo.addBusstopList1(busStops1);
		}
		
		if (MyBusInfo.BUS_BI_DIRECTION == myBusRouteType) {
			busStops2 = MyBusXMLParser.getBusStopsFromHtml(busNum, 1);
			if (busStops2.size() > 0) {
				busInfo.addBusstopList2(busStops2);
			}
		}

		busInfo.traceInfo();

		return busInfo;
	}
	
	public int getBusDistanceToStop(String busNum, String stop, int type) {

		int distance = -1;

		String locReqURI;

		locReqURI = MyBusCommonBase.SERVER
				+ MyBusCommonBase.LOCATION_SERVICE_REQUEST
				+ MyBusCommonBase.KEY_BUS_ID + "=" + busNum + "&"
				+ MyBusCommonBase.KEY_SITE + "=" + MyBusCommonUtil.formatPlainString(stop, "utf-8");
		
		distance = MyBusXMLParser.getDistanceBetweenBusAndStopFromHtml(locReqURI, type);

		return distance;
	}
}
